package com.suning.sawp.in.controller.member;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jxls.common.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.common.base.Function;
import com.google.common.collect.Maps;
import com.suning.sawp.constants.ClerkConstants;
import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.dto.common.EmployeeInfo;
import com.suning.sawp.dto.common.OrgInfo;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.storeman.Category;
import com.suning.sawp.in.controller.DjBaseController;
import com.suning.sawp.in.controller.MyGsonView;
import com.suning.sawp.in.filter.RequestUserHolder;
import com.suning.sawp.intf.storeman.StoreManService;
import com.suning.sawp.member.service.MemExpandConversionService;
import com.suning.sawp.member.vo.MemExpandDataOfCateResponse;
import com.suning.sawp.member.vo.MemExpandDataOfCateVo;
import com.suning.sawp.member.vo.MemExpandDataOfEmployeeResponse;
import com.suning.sawp.member.vo.MemExpandDataOfEmployeeVo;
import com.suning.sawp.member.vo.MemExpandDataOfPlaceResponse;
import com.suning.sawp.member.vo.MemExpandDataOfPlaceVo;
import com.suning.sawp.member.vo.MemExpandDataOfStoreResponse;
import com.suning.sawp.member.vo.MemExpandDataOfStoreVo;
import com.suning.sawp.service.util.DateUtils;
import com.suning.sawp.service.util.ExcelUtils;

/**
 * 门店会员拓展销售转换数据接口 〈一句话功能简述〉<br>
 * 〈功能详细描述〉
 *
 * @author 15050519
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@RequestMapping("/adminPage/memExpandConversion")
public class MemExpandConversionController extends DjBaseController {

	/**
	 * 日志
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(MemExpandConversionController.class);

	/**
	 * 员工信息服务
	 */
	@Autowired
	StoreManService storeManService;

	/**
	 * 销售转换统计服务
	 */
	@Autowired
	MemExpandConversionService memExpandConversionService;

	/**
	 * 总部,大区,分公司查询门店销售转换数据 功能描述: <br>
	 * 〈功能详细描述〉
	 *
	 * @param activityId
	 * @param source
	 * @param mode
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping("/queryExpandDataOfStore.do")
	public MyGsonView queryExpandDataOfStore(Long activityId, Integer source, Integer mode) {
		LOGGER.info("queryExpandDataOfStore enter,activityId={},source={},mode={}", activityId, source, mode);
		ReturnMsg<MemExpandDataOfStoreResponse> retMsg = new ReturnMsg<MemExpandDataOfStoreResponse>();
		if (null == activityId || activityId.longValue() < 0) {
			// 活动ID为空
			retMsg.setError(ErrorCodeConstants.ERR_MEM_0020, (Object) "activityId");
		} else {
			EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
			// 总部，分公司， 大区权限(非门店)
			if (null != employeeInfo && !OrgInfo.ORG_LEVEL.STORE_LEVEL.equals(employeeInfo.getOrgLevel())) {
				try {
					// 查询客户列表
					MemExpandDataOfStoreResponse resp = memExpandConversionService.queryExpandDataOfStore(activityId, source, mode);
					retMsg.setData(resp);
				} catch (Exception e) {
					LOGGER.error("queryExpandDataOfStore error,employeeInfo:" + employeeInfo, e);
					// 数据库异常
					retMsg.setError(ErrorCodeConstants.ERR_0028);
				}
			} else {
				// 店员没有权限
				retMsg.setError(ErrorCodeConstants.ERR_0035);
			}
		}
		return setGsonView(retMsg);
	}

	/**
	 * 店长查询门店8个品类销售转化数据 功能描述: <br>
	 * 〈功能详细描述〉
	 *
	 * @param activityId
	 * @param source
	 * @param mode
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping("/queryExpandDataOfStoreCate.do")
	public MyGsonView queryExpandDataOfStoreCate(Long activityId, Integer source, Integer mode, String storeCode) {
		LOGGER.info("queryExpandDataOfStoreCate enter,activityId={},source={},mode={}", activityId, source, mode);
		ReturnMsg<MemExpandDataOfCateResponse> retMsg = new ReturnMsg<MemExpandDataOfCateResponse>();
		if (null == activityId || activityId.longValue() < 0) {
			// 活动ID为空
			retMsg.setError(ErrorCodeConstants.ERR_MEM_0020, (Object) "activityId");
		} else {
			EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
			if (null == employeeInfo) {
				retMsg.setError(ErrorCodeConstants.ERR_0035);
				return setGsonView(retMsg);
			}
			try {

				if (StringUtils.equals(employeeInfo.getPositionId(), ClerkConstants.STORE_KEEPER)) { // 店长访问
					storeCode = employeeInfo.getStoreCode();
				}

				int orgLevel = Integer.parseInt(employeeInfo.getOrgLevel());
				// 店长权限
				if (orgLevel <= 4 && orgLevel != 3) {
					// 查询客户列表
					MemExpandDataOfCateResponse resp = memExpandConversionService.queryExpandDataOfStoreCate(activityId, storeCode, source, mode);
					retMsg.setData(resp);
				} else {
					// 店员没有权限
					retMsg.setError(ErrorCodeConstants.ERR_0035);
				}
			} catch (Exception e) {
				LOGGER.error("queryExpandDataOfStoreCate error,employeeInfo:" + employeeInfo, e);
				// 数据库异常
				retMsg.setError(ErrorCodeConstants.ERR_0028);
			}
		}
		return setGsonView(retMsg);
	}

	/**
	 * 查询门店品类下店员销售转换数据 功能描述: <br>
	 * 〈功能详细描述〉
	 *
	 * @param activityId
	 * @param cateCode
	 * @param source
	 * @param mode
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping("/queryExpandDataOfEmployee.do")
	public MyGsonView queryExpandDataOfEmployee(Long activityId, String storeCode, String cateCode, Integer source, Integer mode) {
		LOGGER.info("queryExpandDataOfEmployee enter,activityId={},cateCode={},source={},mode={}", activityId, cateCode, source, mode);
		ReturnMsg<MemExpandDataOfEmployeeResponse> retMsg = new ReturnMsg<MemExpandDataOfEmployeeResponse>();
		if (null == activityId || activityId.longValue() < 0) {
			// 活动ID为空
			retMsg.setError(ErrorCodeConstants.ERR_MEM_0020, (Object) "activityId");
		} else if (StringUtils.isBlank(cateCode)) {
			// 品类为空
			retMsg.setError(ErrorCodeConstants.ERR_MEM_0020, (Object) "cateCode");
		} else {
			EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
			// 店长督导获取自身的门店
			if (StringUtils.equals(employeeInfo.getPositionId(), ClerkConstants.STORE_KEEPER) || StringUtils.equals(employeeInfo.getPositionId(), ClerkConstants.SALE_GUIDE)) {
				storeCode = employeeInfo.getStoreCode();
			}

			int orgLevel = Integer.parseInt(employeeInfo.getOrgLevel());
			// 总部，大区，店长,督导权限
			if (orgLevel <= 4 && orgLevel != 3) {
				try {
					// 查询客户列表
					MemExpandDataOfEmployeeResponse resp = memExpandConversionService.queryExpandDataOfEmployee(activityId, storeCode, cateCode, source, mode);
					retMsg.setData(resp);
				} catch (Exception e) {
					LOGGER.error("queryExpandDataOfEmployee error,employeeInfo:" + employeeInfo, e);
					// 数据库异常
					retMsg.setError(ErrorCodeConstants.ERR_0028);
				}
			} else {
				// 店员没有权限
				retMsg.setError(ErrorCodeConstants.ERR_0035);
			}
		}
		return setGsonView(retMsg);
	}

	/**
	 * 查询门店拓展地点销售转换数据 功能描述: <br>
	 * 〈功能详细描述〉
	 *
	 * @param startDate
	 * @param endDate
	 * @param placeName
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping("/queryExpandDataOfPlace.do")
	public MyGsonView queryExpandDataOfPlace(String startDate, String endDate, String placeName) {
		LOGGER.info("queryExpandDataOfPlace enter,startDate={},endDate={},placeName={}", startDate, endDate, placeName);
		ReturnMsg<MemExpandDataOfPlaceResponse> retMsg = new ReturnMsg<MemExpandDataOfPlaceResponse>();
		if (StringUtils.isBlank(startDate)) {
			// 查询开始时间为空
			retMsg.setError(ErrorCodeConstants.ERR_MEM_0020, (Object) "startDate");
		} else if (StringUtils.isBlank(endDate)) {
			// 查询结束时间为空
			retMsg.setError(ErrorCodeConstants.ERR_MEM_0020, (Object) "endDate");
		} else {
			Date startTime = null;
			Date endTime = null;
			// 格式化时间格式
			try {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				startTime = sdf.parse(startDate);
				endTime = sdf.parse(endDate);
			} catch (Exception e) {
				LOGGER.error("queryExpandDataOfPlace error,startDate:" + startDate + ",endDate:" + endDate, e);
				retMsg.setError(ErrorCodeConstants.ERR_MEM_0021, (Object) "startTime,endDate");
				return setGsonView(retMsg);
			}
			EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
			// 店长,督导权限
			if (null != employeeInfo
					&& (StringUtils.equals(employeeInfo.getPositionId(), ClerkConstants.STORE_KEEPER) || StringUtils.equals(employeeInfo.getPositionId(), ClerkConstants.DEPUTY_STORE_KEEPER))) {
				try {
					// 查询客户列表
					MemExpandDataOfPlaceResponse resp = memExpandConversionService.queryExpandDataOfPlace(employeeInfo.getStoreCode(), startTime, endTime, placeName);
					retMsg.setData(resp);
				} catch (Exception e) {
					LOGGER.error("queryExpandDataOfPlace error,employeeInfo:" + employeeInfo, e);
					// 数据库异常
					retMsg.setError(ErrorCodeConstants.ERR_0028);
				}
			} else {
				// 店员没有权限
				retMsg.setError(ErrorCodeConstants.ERR_0035);
			}
		}
		return setGsonView(retMsg);
	}

	/**
	 * 下载门店拓展销售转换数据 功能描述: <br>
	 * 〈功能详细描述〉
	 *
	 * @param activityId
	 * @param source
	 * @param mode
	 * @param response
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping("/downExpandDataOfStore.do")
	public void downExpandDataOfStore(Long activityId, Integer source, Integer mode, HttpServletRequest request, HttpServletResponse response) {
		// 下载数据
		Context context = new Context();
		String fileName = "门店拓展转换数据" + DateUtils.getNowShortStr() + ".xls";
		try {
			List<MemExpandDataOfStoreVo> data = memExpandConversionService.downExpandDataOfStore(activityId, source, mode);
			context.putVar("datas", data);
			String filePath = getFilePath(request, "expandDataOfStore.xls");
			ExcelUtils.downloadTemplateExcel(filePath, fileName, context, response);
		} catch (Exception e) {
			LOGGER.error("downExpandDataOfStore异常", e);
		}

	}

	/**
	 * 获取excel模板文件路径
	 *
	 * @param request
	 * @param fileName
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	private String getFilePath(HttpServletRequest request, String fileName) {
		String rootPath = request.getSession().getServletContext().getRealPath("");
		return rootPath + "/WEB-INF/classes/conf/excel/" + fileName;
	}

	/**
	 * 下载门店品类拓展销售转换数据 功能描述: <br>
	 * 〈功能详细描述〉
	 *
	 * @param activityId
	 * @param source
	 * @param mode
	 * @param response
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping("/downExpandDataOfStoreCate.do")
	public void downExpandDataOfStoreCate(Long activityId, Integer source, Integer mode, String storeCode, HttpServletRequest request, HttpServletResponse response) {
		// 下载数据
		Context context = new Context();
		String fileName = "门店品类拓展转换数据" + DateUtils.getNowShortStr() + ".xls";
		try {
			EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
			// 店长督导获取自身的门店
			if (StringUtils.equals(employeeInfo.getPositionId(), ClerkConstants.STORE_KEEPER) || StringUtils.equals(employeeInfo.getPositionId(), ClerkConstants.SALE_GUIDE)) {
				storeCode = employeeInfo.getStoreCode();
			}
			List<MemExpandDataOfCateVo> data = memExpandConversionService.downExpandDataOfStoreCate(activityId, storeCode, source, mode);
			context.putVar("datas", data);
			String filePath = getFilePath(request, "expandDataOfStoreCate.xls");
			ExcelUtils.downloadTemplateExcel(filePath, fileName, context, response);
		} catch (Exception e) {
			LOGGER.error("downExpandDataOfStore error", e);
		}
	}

	/**
	 * 下载门店品类下员工拓展销售转换数据 功能描述: <br>
	 * 〈功能详细描述〉
	 *
	 * @param activityId
	 * @param cateCode
	 * @param source
	 * @param mode
	 * @param response
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping("/downExpandDataOfEmployee.do")
	public void downExpandDataOfEmployee(Long activityId, String storeCode, String cateCode, Integer source, Integer mode, HttpServletRequest request, HttpServletResponse response) {
		// 下载数据
		Context context = new Context();
		String fileName = "店员拓展转换数据" + DateUtils.getNowShortStr() + ".xls";
		try {
			EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
			// 店长督导获取自身的门店
			if (StringUtils.equals(employeeInfo.getPositionId(), ClerkConstants.STORE_KEEPER) || StringUtils.equals(employeeInfo.getPositionId(), ClerkConstants.SALE_GUIDE)) {
				storeCode = employeeInfo.getStoreCode();
			}
			List<MemExpandDataOfEmployeeVo> data = memExpandConversionService.downExpandDataOfEmployee(activityId, storeCode, cateCode, source, mode);
			context.putVar("datas", data);
			String filePath = getFilePath(request, "expandDataOfEmployee.xls");
			ExcelUtils.downloadTemplateExcel(filePath, fileName, context, response);
		} catch (Exception e) {
			LOGGER.error("downExpandDataOfStore error", e);
		}
	}

	/**
	 * 下载门店拓展地点销售转换数据 功能描述: <br>
	 * 〈功能详细描述〉
	 *
	 * @param startDate
	 * @param endDate
	 * @param placeName
	 * @param response
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping("/downExpandDataOfPlace.do")
	public void downExpandDataOfPlace(String startDate, String endDate, String placeName, HttpServletRequest request, HttpServletResponse response) {
		// 下载数据
		Context context = new Context();
		String fileName = "门店拓展地点转换数据" + DateUtils.getNowShortStr() + ".xls";
		try {
			EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
			List<MemExpandDataOfPlaceVo> data = memExpandConversionService.downExpandDataOfPlace(employeeInfo.getStoreCode(), startDate, endDate, placeName);
			context.putVar("datas", data);
			context.putVar("startDate", startDate);
			context.putVar("endDate", endDate);
			String filePath = getFilePath(request, "expandDataOfPlace.xls");
			ExcelUtils.downloadTemplateExcel(filePath, fileName, context, response);
		} catch (Exception e) {
			LOGGER.error("downExpandDataOfStore error", e);
		}
	}

	/**
	 * 查询活动品类 功能描述: <br>
	 * 〈功能详细描述〉
	 *
	 * @param activityId
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping("/queryCategoryes.do")
	public MyGsonView queryCategoryes(Long activityId) {
		EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
		ReturnMsg<List<Category>> returnMsg = new ReturnMsg<List<Category>>();
		if (null == activityId || activityId.longValue() < 0) {
			// 查询开始时间为空
			returnMsg.setError(ErrorCodeConstants.ERR_MEM_0020, (Object) "activityId");
		} else {
			try {
				List<Category> cates = employeeInfo.getCategoryes();
				// 查询该活动门店拓展品类
				List<Category> activityCates = memExpandConversionService.queryActivityStoreCategorys(activityId, employeeInfo.getStoreCode());
				returnMsg.setData(convertCategorys(activityCates, cates));
			} catch (Exception e) {
				LOGGER.error("queryCategoryes error, activityId=" + activityId, e);
			}
		}
		return setGsonView(returnMsg);
	}

	/**
	 * 处理品类交集 功能描述: <br>
	 * 〈功能详细描述〉
	 *
	 * @param activityCates
	 * @param cates
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	private List<Category> convertCategorys(List<Category> activityCates, List<Category> cates) {
		// 都不为空时
		if (CollectionUtils.isNotEmpty(activityCates) && CollectionUtils.isNotEmpty(cates)) {
			// 转换成MAP集合
			Map<String, Category> cateMap = Maps.uniqueIndex(activityCates, new Function<Category, String>() {
				@Override
				public String apply(Category input) {
					return input.getCategoryCode();
				}
			});
			List<Category> showCates = new ArrayList<Category>();
			// 判断品类是否都存在时,返回该品类
			for (Category cate : cates) {
				if (null != cateMap.get(cate.getCategoryCode())) {
					showCates.add(cate);
				}
			}
			return showCates;
		}
		return Collections.emptyList();
	}

}
